package avicit.bdp.dms.perm.rest;

import avicit.bdp.dms.das.dto.BdpDasCategoryDTO;
import avicit.bdp.dms.perm.dto.DataPermDTO;
import avicit.bdp.dms.perm.service.DataPermService;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2022-11-09
 * @类说明：DataPermRest
 * @修改记录：
 * @注意事项：
 * @主要功能：行权限管理Rest接口
 */
@RestController
@Api(tags = "行权限管理Rest接口")
@RequestMapping("/api/bdp/dms/perm/data")
public class DataPermRest {
    @Autowired
    private DataPermService dataPermService;

    @Autowired
    private ConvertColumnClient convertColumnClient;

    /**
     * 新增数据权限
     *
     * @param dataPermDTO
     * @return
     */
    @PostMapping("/addDataPerm")
    @ApiOperation(value = "新增数据权限")
    public ResponseMsg<Boolean> addDataPerm(@RequestBody DataPermDTO dataPermDTO) {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();

        responseMsg.setResponseBody(this.dataPermService.addDataPerm(dataPermDTO));

        return responseMsg;
    }

    /**
     * 根据模型ID删除权限(业务模块删除模型时同步删除权限)
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据节点ID删除权限,多个id使用英文逗号隔开")
    @ApiImplicitParam(value = "id", name = "id", dataType = "String")
    @DeleteMapping("/deleteDataPermById")
    public ResponseMsg<Integer> deleteDataPermById(
            @RequestParam String id) {
        ResponseMsg<Integer> responseMsg = new ResponseMsg<>();

        this.dataPermService.deleteDataPermById(id);

        return responseMsg;
    }

    /**
     * 修改数据权限
     *
     * @param dataPermDTO
     * @return
     */
    @ApiOperation(value = "修改数据权限")
    @PostMapping("/updateDataPerm")
    public ResponseMsg<Boolean> updateDataPerm(@RequestBody DataPermDTO dataPermDTO) {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();

        responseMsg.setResponseBody(this.dataPermService.updateDataPerm(dataPermDTO));

        return responseMsg;
    }

    /**
     * 根据主键ID查询权限详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键ID查询权限详情")
    @ApiImplicitParam(value = "id", name = "id", dataType = "String")
    @GetMapping("/getDataPermDetail")
    public ResponseMsg<DataPermDTO> getDataPermDetail(@RequestParam String id) {
        ResponseMsg<DataPermDTO> responseMsg = new ResponseMsg<>();

        responseMsg.setResponseBody(this.dataPermService.getDataPermDetail(id));

        return responseMsg;
    }

    /**
     * 数据授权时，获取模型分类树
     * 注意：
     * 1、授权界面中，授权角色获取模型分类树(仅包含已授权模型归属节点的信息)
     *
     * @param roleId
     * @param keyWords
     * @return
     */
    @ApiOperation(value = "查询树结构")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "角色id", name = "roleId", dataType = "String"),
            @ApiImplicitParam(value = "查询关键字", name = "keyWords", dataType = "String")
    })
    @GetMapping("/getCategoryTree")
    public ResponseMsg<List<BdpDasCategoryDTO>> getAllCategory(@RequestParam String roleId,
                                                               @RequestParam(required = false) String keyWords) {
        ResponseMsg<List<BdpDasCategoryDTO>> responseMsg = new ResponseMsg<>();
        List<BdpDasCategoryDTO> result = this.dataPermService.getCategoryTree(roleId, keyWords);
        valueConvert(result);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    /**
     * 获取所有数据源
     * 注意：
     * 1、授权界面，根据角色ID和分类ID获取权限列表
     *
     * @param typeId
     * @param keyWords
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "按条件分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "角色id", name = "roleId", dataType = "String"),
            @ApiImplicitParam(value = "节点分类Id", name = "typeId", dataType = "String"),
            @ApiImplicitParam(value = "查询关键字", name = "keyWords", dataType = "String"),
            @ApiImplicitParam(value = "当前页", name = "pageNo", dataType = "Int"),
            @ApiImplicitParam(value = "每页大小", name = "pageSize", dataType = "Int")
    })
    @GetMapping("/getAuthedDataList")
    @Deprecated
    public ResponseMsg<QueryRespBean<DataPermDTO>> getAuthedDataList(
            @RequestParam String roleId,
            @RequestParam String typeId,
            @RequestParam(required = false) String keyWords,
            @RequestParam(defaultValue = "1", required = false) Integer pageNo,
            @RequestParam(defaultValue = "10", required = false) Integer pageSize) {
        ResponseMsg<QueryRespBean<DataPermDTO>> responseMsg = new ResponseMsg<>();

        responseMsg.setResponseBody(this.dataPermService.getAuthedDataList(roleId, typeId, keyWords, pageNo, pageSize));

        return responseMsg;
    }

    /**
     * 验证SQL语法合法性
     *
     * @param dataPermDTO
     * @return
     */
    @PostMapping("/validSql")
    @ApiOperation(value = "验证SQL语法合法性")
    public ResponseMsg<Boolean> validSql(@RequestBody DataPermDTO dataPermDTO) {
        ResponseMsg responseMsg = new ResponseMsg<>();

        responseMsg.setResponseBody(this.dataPermService.validSql(dataPermDTO));

        return responseMsg;
    }

    /**
     * 生成权限过滤SQL
     *
     * @param dataPermDTO
     * @return
     */
    @ApiOperation(value = "生成权限过滤SQL")
    @PostMapping("/generateSql")
    public ResponseMsg<String> generateSql(@RequestBody DataPermDTO dataPermDTO) {
        ResponseMsg responseMsg = new ResponseMsg<>();

        responseMsg.setResponseBody(this.dataPermService.generateSql(dataPermDTO));

        return responseMsg;
    }

    /**
     * 列举指定表中所有列信息
     *
     * @param tableId
     * @return
     */
    @ApiOperation(value = "列举指定表中所有列信息")
    @ApiImplicitParam(value = "模型表ID", name = "tableId", dataType = "String")
    @GetMapping("/listColumns")
    public ResponseMsg<List<String>> listColumns(String tableId) {
        ResponseMsg<List<String>> responseMsg = new ResponseMsg<>();

        responseMsg.setResponseBody(this.dataPermService.listColumns(tableId));

        return responseMsg;
    }

    /**
     * 数据授权时，获取模型分类树及模型
     * 注意：
     * 1、授权界面中，数据授权时获取未导入的模型分类树及模型（根据角色和已授权模型筛选）
     *
     * @param roleId
     * @return
     */
    @ApiOperation(value = "获取模型分类树及模型")
    @ApiImplicitParam(value = "角色ID", name = "roleId", dataType = "String")
    @GetMapping("/findCategoryAndTableList")
    public ResponseMsg<List<BdpDasCategoryDTO>> findCategoryAndTableList(@RequestParam String roleId) {
        ResponseMsg<List<BdpDasCategoryDTO>> responseMsg = new ResponseMsg<>();

        responseMsg.setResponseBody(this.dataPermService.findCategoryAndTableList(roleId));

        return responseMsg;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     */
    private void valueConvert(List<BdpDasCategoryDTO> bdpDasCategoryDTOList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (BdpDasCategoryDTO bdpDasCategoryDTO : bdpDasCategoryDTOList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, bdpDasCategoryDTO.getCreatedBy());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (BdpDasCategoryDTO bdpDasCategory : bdpDasCategoryDTOList) {
                bdpDasCategory.setCreatedBy(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER,
                        bdpDasCategory.getCreatedBy()));
            }
        }
    }
}
